package com.mjk.manager.api.work;

import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.base.work.BaseWork;
import com.mjk.common.base.work.annotation.BeeApi;
import com.mjk.common.base.work.annotation.BeeWork;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import com.mjk.common.tools.springextend.BeeApplicationListener;
import com.mjk.common.util.ObjectUtils;
import com.mjk.manager.amis.core.model.SysMenu;
import com.mjk.manager.api.dto.ApiDto;
import com.mjk.manager.api.model.ApiModel;
import com.mjk.manager.gen.dto.GenDto;
import com.mjk.manager.gen.work.GenWork;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@BeeWork(work="apis")
public class ApiWork extends BaseWork implements BeeApplicationListener {
	
	@Value(value="${server.port:8080}")
	private String prot ;
	
	@SuppressWarnings("rawtypes")
	@Autowired
	private BeeDBService beeDBService;
	
	@Autowired
	private GenWork gen;


    @BeeApi(name = "获取所有的接口信息", role = "apis#read")
	public BeeResponse getAllApis(ApiDto dto){
		BeeQueryWrapper wrapper = new BeeQueryWrapper(new ApiModel());
		if(ObjectUtils.isNotEmpty(dto.getId())) {
			wrapper.eq(ApiModel::getId,dto.getId());
		}
		if(ObjectUtils.isNotEmpty(dto.getMenuId())) {
			wrapper.eq(ApiModel::getMenuId,dto.getMenuId());
		}
        if (ObjectUtils.isNotEmpty(dto.getModelId())) {
            wrapper.eq(ApiModel::getModelId, dto.getModelId());
        }
		if(ObjectUtils.isNotEmpty(dto.getApiName())){
			wrapper.like(ApiModel::getApiName,dto.getApiName());
		}
		if(ObjectUtils.isNotEmpty(dto.getApiType())){
			wrapper.eq(ApiModel::getApiType,dto.getApiType());
		}
		if(ObjectUtils.isNotEmpty(dto.getApiWork())){
			wrapper.eq(ApiModel::getApiWork,dto.getApiWork());
		}
		if(ObjectUtils.isNotEmpty(dto.getIsDynamic())){
			wrapper.eq(ApiModel::getIsDynamic,dto.getIsDynamic());
		}
		if(isPage(dto)) {
			wrapper.setPage(dto.getPageStart(),dto.getPageSize());
            return BeeError.BEE_SUC.tranceError(beeDBService.findManyByWrapperWithPage(wrapper));
		}else {
            return BeeError.BEE_SUC.tranceError(beeDBService.findManyByWrapper(wrapper));
		}
	}
	
	@SuppressWarnings("unchecked")
	//@BeeApi(limiter=100,name="获取接口树菜单到接口",role = ApiRole.UPDATE)
	public BeeResponse getApiTree(ApiDto dto){
		BeeQueryWrapper scWrapper = new BeeQueryWrapper(new SysMenu());
		List<Object> result = new ArrayList<>();
        List<SysMenu> menus = beeDBService.findManyByWrapper(scWrapper);

		BeeQueryWrapper apiWrapper = new BeeQueryWrapper(new ApiModel());
		if(ObjectUtils.isNotEmpty(dto.getApiName())){
			apiWrapper.like(ApiModel::getApiName,dto.getApiName());
		}
		if(ObjectUtils.isNotEmpty(dto.getApiType())){
			apiWrapper.eq(ApiModel::getApiType,dto.getApiType());
		}
		if(ObjectUtils.isNotEmpty(dto.getApiWork())){
			apiWrapper.eq(ApiModel::getApiWorkName,dto.getApiWork());
		}
		if(ObjectUtils.isNotEmpty(dto.getIsDynamic())){
			apiWrapper.eq(ApiModel::getIsDynamic,dto.getIsDynamic());
		}
        List<ApiModel> apis = beeDBService.findManyByWrapper(apiWrapper);
		for(ApiModel api : apis) {
			api.setParentId(api.getModelId());
			api.setApipostMenuId(api.getMenuId());
		}
		result.addAll(menus);
		result.addAll(apis);
		return BeeError.BEE_SUC.tranceError(result);
	}
		
	@SuppressWarnings("unchecked")
	@GlobalTransactional(lockRetryInternal = 100)
    @BeeApi(name = "更新接口", role = "apis#write")
	public BeeResponse updateApi(ApiModel dto){
		if(ObjectUtils.isNotEmpty(dto.getSelectSql())){
			dto.setType("1");
		}else if(ObjectUtils.isNotEmpty(dto.getProcedureName())){
			dto.setType("2");
		}else {
			dto.setType("1");//如果都不传默认为SQL
		}
		//create url
		if("1".equals(dto.getApiType())){
			dto.setUrl("http://localhost:"+prot+"/ld/common/dict/"+dto.getApiWork()+"?method="+dto.getApiMethod());
		}else {
			dto.setIsDynamic("1");
		}
		if(ObjectUtils.isEmpty(dto.getId())){
			beeDBService.insert(dto);
		}else{
			BeeQueryWrapper apiWrapper = new BeeQueryWrapper(dto);
			apiWrapper.eq(ApiModel::getModelId,dto.getId());
			beeDBService.update(apiWrapper);
		}
		GenDto gDto;
		//动态编译生产bean
		if("1".equals(dto.getApiType())){
			BeeQueryWrapper apiWrapper = new BeeQueryWrapper(new ApiModel());
			apiWrapper.eq(ApiModel::getApiWork,dto.getApiWork()).eq(ApiModel::getIsDynamic,"1").eq(ApiModel::getId,dto.getId());
            List<ApiModel> models = beeDBService.findManyByWrapper(apiWrapper);
			gDto = new GenDto(dto, models);
		}else {
			gDto = new GenDto(dto);
		}
		gen.publish(gDto);
		return BeeError.BEE_SUC.tranceError("");
	}

	/**
	 * 更新接口
	 * @param dto
	 * @return
	 */
	public BeeResponse updateApiParams(ApiModel dto){
		needParams(dto,ApiModel::getId);
		BeeQueryWrapper wrapper = new BeeQueryWrapper(dto);
		wrapper.eq(ApiModel::getId,dto.getId());
		beeDBService.update(wrapper);
		return BeeError.BEE_SUC.tranceError();
	}

	/**
	 * 分配接口到菜单
	 * @param dto
	 * @return
	 */
	public BeeResponse dispathApi(ApiDto dto){
		needParams(dto,ApiDto::getId,ApiDto::getMenuId);
		ApiModel api = new ApiModel();
		api.setMenuId(dto.getMenuId());
		BeeQueryWrapper wrapper = new BeeQueryWrapper(api);
		wrapper.in(ApiModel::getId, Arrays.asList(dto.getId().split(",")));
		beeDBService.update(wrapper);
		return BeeError.BEE_SUC.tranceError();
	}
	/**
	 * 删除接口
     */
	public BeeResponse delApi(ApiDto dto) {
		needParams(dto, ApiDto::getId);
		BeeQueryWrapper apiWrapper = new BeeQueryWrapper(new ApiModel());
		apiWrapper.eq(ApiModel::getModelId,dto.getId());
		beeDBService.delete(apiWrapper);
		return BeeError.BEE_SUC.tranceError();
	}


}
